package com.mrjy.maintain.bo;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.mrjy.common.entity.PromoteDetail;
import com.mrjy.common.entity.PromoteSettleInfo;
import com.mrjy.common.entity.TransferInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.maintain.dao.IMingrenTeamInfoDao;
import com.mrjy.maintain.dao.IPartnerInfoDao;
import com.mrjy.maintain.dao.IPromoteDetailDao;
import com.mrjy.maintain.dao.IServiceStationInfoDao;
import com.mrjy.maintain.dao.ITeacherInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserScancodeInfoDao;
import com.mrjy.maintain.dto.PromoteDetailDTO;
import com.mrjy.maintain.util.RoleInfoEnum;
import com.mrjy.maintain.util.SharingProportionEnum;
import com.mrjy.payment.bo.TransferPaymentBo;
import com.mrjy.payment.dao.ITransferInfoDao;
import com.mrjy.share.dao.IDistributorInfoDao;
import com.mrjy.share.dao.IDistributorTeamInfoDao;
import com.mrjy.share.dto.DistributorInfoDTO;

@Service("promoteDetailBo")
public class PromoteDetailBo implements IPromoteDetailBo{
	
	@Resource
	private IUserScancodeInfoDao userScanCodeInfoDao;
	
	@Resource
	private IUserInfoDao userInfoDao;
	
	@Resource
	private IPromoteDetailDao promoteDetailDao;
	@Resource
	private IDistributorInfoDao distributorInfoDao;
	@Resource
	private IDistributorTeamInfoDao distributorTeamInfoDao;
	
	@Resource
	private IPartnerInfoDao partnerInfoDao;
	
	@Resource
	private IServiceStationInfoDao serviceStationInfoDao;
	@Resource
	private IMingrenTeamInfoDao mingrenTeamInfoDao;
	
	@Resource
	private ITeacherInfoDao teacherInfoDao;
	
	@Resource
	private IPromoteSettleInfoBo promoteSettleInfoBo;
	
	@Resource
    ITransferInfoDao transferInfoDao;
	
	@Resource
    TransferPaymentBo transferPaymentBo;

	@Override
	public Object queryPromoteDetailPageForBack(PromoteDetailDTO dto,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == userInfo ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		//如果是分销商、分销商&学校、合作方、合作方&学校、服务站、服务站&学校管理员，进行数据过滤
		if(userInfo.getRoleId().intValue() == RoleInfoEnum.SYS_ADMIN.getRoleId()
				|| userInfo.getRoleId().intValue() == RoleInfoEnum.NORMAL_ADMIN.getRoleId()
				|| userInfo.getRoleId().intValue() == RoleInfoEnum.FINANCE_ADMIN.getRoleId()
				|| userInfo.getRoleId().intValue() == RoleInfoEnum.OPERATOR_ADMIN.getRoleId()
				|| userInfo.getRoleId().intValue() == RoleInfoEnum.DELIVERY_ADMIN.getRoleId()
				|| userInfo.getRoleId().intValue() == RoleInfoEnum.IT_ADMIN.getRoleId()){
			dto.setBelongId(null);
		}else{
			dto.setBelongId(userInfo.getId());
		}
		PromoteDetailDTO totalDTO = promoteDetailDao.queryTotalMoneyPromoteForBack(dto);
		if(totalDTO != null  ){
			List<PromoteDetailDTO> list = promoteDetailDao.queryPromoteDetailPageForBack(dto);
			if(list != null && list.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("rows", list);
				map.put("totalDTO", totalDTO);
				map.put("total", totalDTO.getTotalPromote());
			}else {
				map.put("err_code", 1);
				map.put("err_msg", "无数据");
				map.put("rows", list);
				map.put("totalDTO", totalDTO);
				map.put("total", 0);
			}
		}else {
			map.put("err_code", 2);
			map.put("err_msg", "无数据");
			map.put("rows", null);
			map.put("totalDTO", null);
			map.put("total", 0);
		}
		
		map.put("roleId", userInfo.getRoleId());
		return map;
	}


	@Override
	public Object txUpdateSettleStatus(PromoteDetail info,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		List<PromoteSettleInfo> list = new ArrayList<PromoteSettleInfo>();
		if (info.getIds()!=null && info.getIds().length>0) {
			for (int id : info.getIds()) {
				PromoteDetail detail = promoteDetailDao.selectById(id);
				if (detail.getSettleStatus().equals("1")) {
					map.put("err_code", 400);
					map.put("err_msg", "订单号为"+detail.getCode()+"的推广明细已经结算,请不要重复结算!");
					return map;
				}
				PromoteSettleInfo settleInfo = new PromoteSettleInfo();
				settleInfo.setPromoteId(id);
				settleInfo.setSettleTime(new Timestamp(System.currentTimeMillis()));
				//根据promoteId查询分成比例
				if (detail.getSharingProportion()== SharingProportionEnum.NORMAL.getSharingProportion().intValue()) { //10%微信自动结算  25% 40%..财务管理员结算
					settleInfo.setDesc("已自动到账推广者微信账户");
				}else {
					settleInfo.setDesc("财务管理员已结算");
				}
				list.add(settleInfo);
			}
		}
		//新增结算明细
		try {
			promoteSettleInfoBo.insertBatch((list));
			info.setSettleDesc("线下结算");
			promoteDetailDao.updateSettleStatus(info);
			map.put("err_code", 200);
			map.put("err_msg", "结算成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "发生异常");
		}
		return map;
		
	}


	@Override
	public Object querySumPromoteDetailByUserId(PromoteDetailDTO dto, HttpSession session) {
		Map<String, Object> map = new HashMap<String,Object>();
		UserInfo ui = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(ui == null){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		//查看当前用户是什么类型的推广者
		DistributorInfoDTO diDTO = distributorInfoDao.queryNeedInfoByUserId(dto.getRecommendId());
		if(diDTO == null){
			map.put("err_code", 101);
			map.put("err_msg", "用户不是推广者");
			return map;
		}else{
			//查询用户的总收益（1,2级扫码推广+团队推广） ps：普通推广者就没有团队推广
			 PromoteDetailDTO sumDTO = promoteDetailDao.querySumMoneyByRecommendId(dto);
			if(sumDTO != null){
				//历史总收益
				diDTO.setTotalMoney(sumDTO.getTotalDivideMoney().setScale(2,BigDecimal.ROUND_HALF_UP));
				diDTO.setTotalUnSettleMoney(sumDTO.getTotalNotSettleMoney().setScale(2,BigDecimal.ROUND_HALF_UP));
			}
			
			//查询用户一级推广和二级推广人数
			sumDTO = promoteDetailDao.countFirstAndSecondPromote(dto);
			//一级推广总人数
			diDTO.setTotalFirstPromote(sumDTO.getTotalFirstPromote());
			//二级推广总人数
			diDTO.setTotalSecondPromote(sumDTO.getTotalSecondPromote());
			diDTO.setFirstVipCount(sumDTO.getFirstVipCount());
			diDTO.setSecondVipCount(sumDTO.getSecondVipCount());
			
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("info", diDTO);
		}
		return map;
	}


	@Override
	public Object queryPromoteDetailListByRecommendId(PromoteDetailDTO dto,HttpSession session) {
		Map<String, Object> map = new HashMap<String,Object>();
		UserInfo ui = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(ui == null){
			map.put("err_code", -101);
			map.put("err_msg", "用户没有登录或登录失效");
			return map;
		}
		if(dto.getRecommendId() == null){
			map.put("err_code", -102);
			map.put("err_msg", "推广者id为空");
			return map;
		}
		PromoteDetailDTO sumDTO = promoteDetailDao.querySumMoneyByRecommendId(dto);
		if(sumDTO != null){
			List<PromoteDetailDTO> listDTO = promoteDetailDao.queryPromoteDetailListByRecommendId(dto);
			if(listDTO != null && listDTO.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("rows",listDTO);
				map.put("totalMoney", sumDTO.getTotalDivideMoney());//子查询中的金钱合计
				map.put("totalPromote", sumDTO.getTotalPromote());
			}else{
				map.put("err_code", 1);
				map.put("err_msg", "没有相关数据");
				map.put("rows", null);
				map.put("totalMoney", 0);//子查询中的金钱合计
				map.put("totalPromote", 0);
			}
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "没有相关数据");
			map.put("rows", null);
			map.put("totalMoney", 0);//子查询中的金钱合计
			map.put("totalPromote", 0);
		}
		
		
		return map;
	}
	


	@Override
	public Object queryPromoterMoneyListByRecommendId(PromoteDetailDTO dto) {
		Map<String, Object> map = new HashMap<String,Object>();
		int teamMemberNum = distributorTeamInfoDao.queryTeamMemberNumByRecommendId(dto.getRecommendId());
		DistributorInfoDTO disDTO = distributorInfoDao.queryByUserId(dto.getRecommendId());
		if(disDTO == null){
			map.put("err_code", -1);
			map.put("err_msg", "该用户不是推广者，请联系系统管理员处理！");
			return map ;
		}
		List<PromoteDetailDTO> listDTO = promoteDetailDao.queryPromoterMoneyListByRecommendId(dto);
		//团队成员带给负责人的二级收益
		PromoteDetailDTO totalDTO = promoteDetailDao.queryTeamSumMoneyByRecommendId(dto);
		//团队成员获得的一级收益(自定义分成比例算出)
		PromoteDetailDTO totalCostDTO = promoteDetailDao.queryTeamSumMoneyCostByRecommendId(dto);
		Double incomeForMe = 0.0 ;//团队负责人获得的收益(负责人分成比例-成员自定义比例 算出的)
		Double incomeForTeam = 0.0 ;//团队成员获得的收益(自定义分成比例求得)
		if(totalDTO != null){
			incomeForMe = totalDTO.getTotalDivideMoney().doubleValue();
		}
		if(totalCostDTO != null){
			incomeForTeam = totalCostDTO.getTotalDivideMoney().doubleValue();
		}
		if(listDTO != null && listDTO.size() > 0){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", listDTO);
			map.put("teamMemberNum", teamMemberNum);
			map.put("IncomeForMe", incomeForMe);
			map.put("IncomeForTeam", incomeForTeam);
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "无数据");
			map.put("rows", null);
			map.put("teamMemberNum", teamMemberNum);
			map.put("IncomeForMe", incomeForMe);
			map.put("IncomeForTeam", incomeForTeam);
		}
		
		return map;
	}


	@Override
	public Object queryTeanMemberDetailListByDistributorIdAndUserId(PromoteDetailDTO dto) {
		Map<String, Object> map = new HashMap<String,Object>();
		PromoteDetailDTO totalDTO = promoteDetailDao.queryTeanMemberTotalMoneyByDistributorIdAndRecommendId(dto);
		if(totalDTO != null){
			List<PromoteDetailDTO> listDTO = promoteDetailDao.queryTeanMemberDetailListByDistributorIdAndRecommendId(dto);
			if(listDTO != null && listDTO.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("rows", listDTO);
				map.put("totalMoney", totalDTO.getTotalDivideMoney());
				map.put("totalPromote", totalDTO.getTotalPromote());
			}else{
				map.put("err_code", 1);
				map.put("err_msg", "无数据");
				map.put("rows", null);
				map.put("totalMoney", totalDTO.getTotalDivideMoney());
				map.put("totalPromote", totalDTO.getTotalPromote());
			}
		}else {
			map.put("err_code", 2);
			map.put("err_msg", "无数据");
			map.put("rows", null);
			map.put("totalMoney", 0);
			map.put("totalPromote", 0);
		}
		return map;
	}


	@Override
	public Object queryDistributorDetailListByDistributorId(PromoteDetailDTO dto) {
		Map<String, Object> map = new HashMap<String,Object>();
		DistributorInfoDTO disDTO = distributorInfoDao.queryById(dto.getDistributorId());
		if(disDTO != null){
			if("51".equals(disDTO.getDistributorType()) || "52".equals(disDTO.getDistributorType())
					|| "7".equals(disDTO.getDistributorType())){
				dto.setIsLongTermExpire("1");
			}else {
				dto.setIsLongTermExpire("0");
			}
		}
		List<PromoteDetailDTO> listDTO = promoteDetailDao.queryDistributorDetailListByDistributorId(dto);
		if(listDTO != null && listDTO.size() > 0){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", listDTO);
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "无数据");
			map.put("rows", null);
		}
		return map;
	}


	@Override
	public Object exportExl(PromoteDetailDTO dto, HttpServletResponse response, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		Map<String, Object> result = (Map<String, Object>) this.queryPromoteDetailPageForBack(dto,session);
		List<PromoteDetail> list = new ArrayList<PromoteDetail>();
		if (result.get("err_msg") .equals("无数据") || result.get("rows") == null) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		List<PromoteDetailDTO> dataset = (List<PromoteDetailDTO>) result.get("rows");
		try {
			//封装数据
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (PromoteDetailDTO promoteDetailDTO : dataset) {
				PromoteDetail promoteDetail = new PromoteDetail();
				if (StringUtils.isNotBlank(promoteDetailDTO.getCode())) {
					promoteDetail.setCode(promoteDetailDTO.getCode());
				}
				if (StringUtils.isNotBlank(promoteDetailDTO.getCostName())) {
					promoteDetail.setCostName(promoteDetailDTO.getCostName());
				}
				if (StringUtils.isNotBlank(promoteDetailDTO.getUserName())) {
					promoteDetail.setUserName(promoteDetailDTO.getUserName());
				}
				if (StringUtils.isNotBlank(promoteDetailDTO.getCompleteTimeString())) {
					promoteDetail.setCompleteTime(new Timestamp(sdf.parse(promoteDetailDTO.getCompleteTimeString()).getTime()));
				}
				if (StringUtils.isNotBlank(promoteDetailDTO.getRegisterDateString())) {
					promoteDetail.setRegisterDate(new Timestamp(sdf.parse(promoteDetailDTO.getRegisterDateString()).getTime()));
				}
				promoteDetail.setMoney(promoteDetailDTO.getMoney());
				promoteDetail.setRecommendName(promoteDetailDTO.getRecommendName());
				promoteDetail.setRecommendCode(promoteDetailDTO.getRecommendCode());
				promoteDetail.setSharingProportion(promoteDetailDTO.getSharingProportion());
				promoteDetail.setDivideMoney(promoteDetailDTO.getDivideMoney());
				promoteDetail.setMobilePhone(promoteDetailDTO.getMobilePhone());
				if (promoteDetailDTO.getSettleStatus().equals("0")) {
					promoteDetail.setSettleStatus("待结算");
				}
				if (promoteDetailDTO.getSettleStatus().equals("1")) {
					promoteDetail.setSettleStatus("已结算");
				}
				list.add(promoteDetail);
			}
			ExcelUtil.writeExcel(response, "推广明细"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", list, PromoteDetail.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}


	@Override
	public Object txSettleByIds(PromoteDetailDTO dto, Map<String, Object> map) {
		List<PromoteSettleInfo> promoteSettleList = new ArrayList<PromoteSettleInfo>();
		int success_count = 0 ;
		int fail_count = 0 ;
		StringBuffer successBuffer = new StringBuffer() ;
		StringBuffer failBuffer = new StringBuffer();
		for(Integer id : dto.getIds()){
			PromoteDetail info = promoteDetailDao.queryNotSettleById(id);
			if(null == info){
				fail_count ++ ;
				failBuffer.append("结算记录id为"+id+"的记录已结算或者查询不到 <br/>");
			}else{
				//企业付款零钱到推广者微信账户
				TransferInfo transInfo = new TransferInfo();
				transInfo.setAmount(info.getDivideMoney());
				transInfo.setPartnerTradeNo(info.getProCode().replaceAll("_", ""));
				transInfo.setUserId(info.getRecommendId());
				transInfo.setPaymentDesc("会员或课程推广成功分成收入");
				@SuppressWarnings("unchecked")
				Map<String,Object> returnMap = (Map<String, Object>) transferPaymentBo.weChatTransferPay(transInfo);
				if(returnMap != null ){
					if("200".equals(returnMap.get("err_code"))){//付款成功
						transInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
						transInfo.setCompleteTime(Timestamp.valueOf((String) returnMap.get("paymentTime")));
						transInfo.setDisabledFlag("0");
						transInfo.setTransferStatus("1");
						transInfo.setErrCode((String) returnMap.get("err_code"));
						transInfo.setErrCodeDes((String) returnMap.get("err_code_des"));
						transInfo.setPaymentId(info.getPaymentId());
						transferInfoDao.insert(transInfo);
						
						info.setSettleStatus("1");
						info.setSettleDesc("线上结算");
						promoteDetailDao.updateSettleStatusById(info);
						
						PromoteSettleInfo settleInfo = new PromoteSettleInfo();
						settleInfo.setPromoteId(id);
						settleInfo.setSettleTime(new Timestamp(System.currentTimeMillis()));
						settleInfo.setDesc("财务管理员已结算");
						promoteSettleList.add(settleInfo);
						
						success_count ++ ;
						successBuffer.append("订单"+transInfo.getPartnerTradeNo() + "结算成功 <br/>");
					}else{//付款失败
						transInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
						transInfo.setDisabledFlag("0");
						transInfo.setTransferStatus("0");
						transInfo.setErrCode((String) returnMap.get("err_code"));
						transInfo.setErrCodeDes((String) returnMap.get("err_code_des"));
						transInfo.setPaymentId(info.getPaymentId());
						transferInfoDao.insert(transInfo);
						
						fail_count ++ ;
						failBuffer.append("订单"+transInfo.getPartnerTradeNo() + "结算失败，失败原因："+ (String) returnMap.get("err_code_des") +" <br/>");
					}
				}else {
					transInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
					transInfo.setDisabledFlag("0");
					transInfo.setTransferStatus("0");
					transInfo.setErrCode("201");
					transInfo.setErrCodeDes("企业付款时没有返回消息");
					transInfo.setPaymentId(info.getPaymentId());
					transferInfoDao.insert(transInfo);
					
					fail_count ++ ;
					failBuffer.append("订单"+transInfo.getPartnerTradeNo() + "结算失败，失败原因：企业付款时没有返回消息 <br/>");
				}
			}
		}
		if(success_count > 0 && promoteSettleList.size() > 0){
			promoteSettleInfoBo.insertBatch((promoteSettleList));
		}
		map.put("err_code", "200");
		map.put("err_msg", "结算的总数："+ dto.getIds().length + "条 , 其中成功结算的记录数："+ success_count+"条，结算失败的记录数：" + fail_count + "条,其中：</br>"
				+ "<strong>结算成功的记录：</strong></br>" + successBuffer.toString() + "<strong>结算失败的记录：</strong><br/>" + failBuffer.toString());
		return map ;
	}


	@Override
	public Object queryMyPromoterList(PromoteDetailDTO dto, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//		if(null == loginUser ){
//			map.put("err_code", -1);
//			map.put("err_msg", "用户未登录");
//			return map;
//		}
		if (dto == null) {
			map.put("err_code", 400);
			map.put("err_msg", "参数错误");
			return map;
		}
		List<PromoteDetailDTO> list = null;
		//一级推广列表
		if (dto.getPromoteType().equals("first")) {
			list = promoteDetailDao.queryFirstPromoterList(dto);
		//二级推广列表
		}else if (dto.getPromoteType().equals("second")) {
			list = promoteDetailDao.querySecondPromoterList(dto);
		}
		map.put("err_code", 200);
		map.put("err_msg", "查询成功");
		map.put("rows", list);
		return map;
	}

}
